import { useEffect, useState } from "react"
import { Alert, Button, message, Space } from "antd"
import { useDispatch } from 'react-redux'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import * as apis from "../../apis/group"
import * as groupUserApis from "../../apis/groupUser"
import useCURD from "../../hooks/useCURD"
import CommonModalForm from "../../components/common/CommonModalForm"
import CommonTable, { createColumn } from "../../components/common/CommonTable"
import UserPicker from "../../components/UserPicker"
import { queryUserGroupsAction } from '../../store/actions/userActions'
import CommonFilterItem from "../../components/common/CommonFilterItem"
import useRowSelection from "../../hooks/useRowSelection"

const GroupUser = ({
  groupId
}) => {

  const {
    listData,
    loading,
    handleDeleteOne,
    doQueryList,
    changeQueryValues,
    query,
  } = useCURD({
    apis: groupUserApis,
    moduleName: '用户',
    initQuery: false
  })

  useEffect(() => {
    changeQueryValues({
      groupId,
      filter: ''
    })
  }, [groupId])

  useEffect(() => {
    if (groupId) {
      doQueryList()
    }
  }, [query])

  const columns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '用户id',
      width: 100
    },
    createColumn.searchResult({
      dataIndex: 'fullName',
      title: '名称',
      width: 200,
      searchWord: query.filter
    }),
    {
      key: 'email',
      dataIndex: 'email',
      title: '邮箱'
    },
    {
      key: 'tenantId',
      dataIndex: 'tenantId',
      title: '租户',
      width: 120
    },
    {
      key: 'action',
      title: '操作',
      width: 50,
      align: 'center',
      render: (rowData) => {
        return <Space>
          <Button
            size="small"
            type="primary"
            danger
            onClick={() => {
              handleDeleteOne({
                userId: rowData.id,
                groupId
              })
            }}
          ><DeleteOutlined /></Button>
        </Space>
      }
    }
  ]

  const handlePickUser = async (userIds) => {
    try {
      for (let userId of userIds) {
        await groupUserApis.createOne({
          groupId,
          userId
        })
      }
      doQueryList()
      message.success('添加用户成功')
    } catch (error) {
      message.error('添加用户失败')
    }
  }

  return <div className="page-wrap">
    <div className="page-head">
      <UserPicker
        disabled={!Boolean(groupId)}
        onPick={handlePickUser}
        disabledKeys={listData.map(el => el.id)}
      ></UserPicker>
      <Space>
        <CommonFilterItem.Search
          label="名称"
          field="filter"
          queryValues={query}
          onChangeQueryValues={changeQueryValues}
        ></CommonFilterItem.Search>
      </Space>
    </div>
    <div className="page-body">
      {
        Boolean(groupId) ?
          <CommonTable
            loading={loading}
            dataSource={listData}
            columns={columns}
          ></CommonTable> :
          <Alert
            type="warning"
            showIcon
            message="从左边的列表中选择一个组"
          ></Alert>
      }
    </div>
  </div>
}

const GroupList = ({
  onChangeGroup
}) => {
  const dispatch = useDispatch()

  const {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection
  } = useRowSelection({
    multiple: false
  })


  const {
    listData,
    loading,
    handleCreate,
    handleModify,
    handleDeleteOne,
    handleCancelForm,
    handleSubmit,
    formData,
    formVisible,
    formTitle,
  } = useCURD({
    apis,
    moduleName: '用户组',
    getResData: res => res,
    changeListSuccessCallBack: () => {
      dispatch(queryUserGroupsAction())
    }
  })

  const formItems = [
    {
      name: 'id',
      label: '用户组ID',
      required: true,
      hideInEdit: true
    },
    {
      name: 'name',
      label: '名称',
      required: true
    }
  ]

  const columns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '用户组ID',
      width: 100
    },
    {
      key: 'name',
      dataIndex: 'name',
      title: '组名'
    },
    {
      key: 'action',
      title: '操作',
      width: 90,
      align: 'center',
      render: (rowData) => {
        return <Space onClick={(e) => { e.stopPropagation() }}>
          <Button
            size="small"
            type="primary"
            onClick={() => { handleModify(rowData) }}
          ><EditOutlined /></Button>
          <Button
            size="small"
            type="primary"
            danger
            onClick={() => {
              handleDeleteOne({
                id: rowData.id
              })
            }}
          ><DeleteOutlined /></Button>
        </Space>
      }
    }
  ]

  useEffect(() => {
    if (selectedRowKeys.length) {
      onChangeGroup(selectedRowKeys[0])
    }
  }, [selectedRowKeys])

  return <div className="page-wrap">
    <CommonModalForm
      title={formTitle}
      visible={formVisible}
      initValues={formData}
      formItems={formItems}
      onCancel={handleCancelForm}
      onSubmit={handleSubmit}
    ></CommonModalForm>
    <div className="page-head">
      <Button type="primary" onClick={handleCreate}>创建用户组</Button>
    </div>
    <div className="page-body">
      <CommonTable
        dataSource={listData}
        columns={columns}
        loading={loading}
        rowSelection={rowSelection}
        onRow={(rowData) => ({
          onClick: () => { setSelectedRowKeys([rowData.id]) },
          style: { cursor: 'default' }
        })}
      ></CommonTable>
    </div>
  </div>
}

const IdmGroup = () => {
  const [groupId, setGroupId] = useState(null)
  return <div style={{
    display: 'flex',
    height: '100%'
  }}>
    <div style={{ width: 400, flexShrink: 0 }}>
      <GroupList onChangeGroup={setGroupId} />
    </div>
    <div style={{ flex: 1, overflow: 'auto' }}>
      <GroupUser groupId={groupId} />
    </div>
  </div>
}

export default IdmGroup